<template>
	<div>
		<el-dialog :fullscreen="fullscreen" :title="stateTitle" :visible.sync="show" width="1300px" @closed="cancel">

<!-- 			<div slot="title">
				<div class="app-space-between">
					<div style="color: #606266;font-weight: bold;">{{stateTitle}}</div>
					<div style="cursor: pointer;font-size: 25px;">
					</div>
				</div>
			</div> -->
			<el-form ref="formData" :rules="formRules" :model="formData" label-width="80px" class="demo-ruleForm">
				<el-row>
					<el-col :span="17">
						<el-row>
							<el-col :span="24">
								<el-form-item label="标题" label-width="50px" prop="title">
                  <div>
                    <span v-if="state == 3">{{formData.title}}</span>
                    <el-input v-else v-model="formData.title" placeholder="请输入标题" show-word-limit maxlength="300"></el-input>
                  </div>
								</el-form-item>
							</el-col>
						</el-row>
						<el-row>
							<el-col :span="24">
								<el-form-item label="" label-width="10px" prop="content">
                  <div>
                    <div class="quill-div" v-if="state == 3" v-html="formData.content"></div>
                    <quill-edit v-else v-model="formData.content" :height="465"></quill-edit>
                  </div>
								</el-form-item>
							</el-col>
						</el-row>

            <el-row>
            	<el-col :span="24">
            		<el-form-item label="附件" label-width="50px">
                  <el-upload
                    :before-upload="beforeAvatarUpload"
                    :class="state == 3 ? 'upload-demo-look' : 'upload-demo'"
                    :action="uploadImgUrl"
                    :headers="headers"
                    name="file"
                    :on-success="onSuccess"
                    :on-preview="onPreview"
                    multiple
                    :before-remove="beforeRemove"
                    :disabled="state == 3"
                    :accept="accept"
                    :file-list="fileList">
                    <el-button size="small" v-if="state != 3" type="primary">点击上传</el-button>
                    <div slot="tip" v-if="state != 3" class="el-upload__tip">文件只能上传{{accept}}格式,大小不能超50MB。预览请点击下方显示的文件。</div>
                  </el-upload>
            		</el-form-item>
            	</el-col>
            </el-row>
					</el-col>
					<el-col :span="1" style="height: 100px;"></el-col>
					<el-col :span="5">
						<el-form-item label="作者" prop="author">
              <div>
                <span v-if="state == 3">{{formData.author}}</span>
                <el-input v-else v-model="formData.author" placeholder="请输入作者" style="width: 200px;"></el-input>
              </div>
						</el-form-item>
<!-- 						<el-form-item label="编辑">
							<el-input v-model="input" placeholder="请输入编辑" style="width: 200px;"></el-input>
						</el-form-item> -->
						<el-form-item label="所属栏目" prop="categoryId">
              <div>
                <div v-if="state == 3">{{categoryIdName}}</div>
                <div v-else @click="selectClick(1)">
                  <div class="select-column" v-if="categoryIdName">{{categoryIdName}}</div>
                  <div class="select-column" v-else style="color: #C0C4CC;">
                    请选择
                    <span class="el-icon-arrow-right"></span>
                  </div>
                </div>
              </div>
						</el-form-item>
						<el-form-item label="同时发布" >
              <div>
                <div v-if="state == 3">{{selectColumn}}</div>
                <div v-else @click="selectClick(2)">
                  <div class="select-column" v-if="selectColumn">{{selectColumn}}</div>
                  <div class="select-column" v-else style="color: #C0C4CC;">
                    请选择
                    <span class="el-icon-arrow-right"></span>
                  </div>
                </div>
              </div>
						</el-form-item>

						<el-form-item label="上传图片" prop="coverImage">
							<div @click="handleUpImage">
								<el-image v-if="formData.coverImage"
								  style="width: 200px; height: 150px"
								  :src="images"
								  fit="cover"></el-image>
								<i class="el-icon-picture" v-else style="font-size: 100px;cursor: pointer;"></i>
							</div>
						</el-form-item>

						<el-form-item label="发布平台" style="pointer-events: none;">
							<el-checkbox v-model="checked" :disabled="state == 3">PC</el-checkbox>
						</el-form-item>

						<el-form-item label="发布时间" prop="publishTime">
              <div>
                <div v-if="state == 3">{{formData.publishTime | $timeReplaceFilter}}</div>
                <el-date-picker v-else v-model="formData.publishTime" type="date" value-format="yyyy/MM/dd"
                	style="width: 200px;" placeholder="选择发布时间">
                </el-date-picker>
              </div>
						</el-form-item>
						<el-form-item label="下线时间">
              <div>
                <div v-if="state == 3">{{formData.offlineTime | $timeReplaceFilter}}</div>
							<el-date-picker v-else v-model="formData.offlineTime" type="date" value-format="yyyy/MM/dd"
								style="width: 200px;" placeholder="选择下线时间">
							</el-date-picker>
              </div>
						</el-form-item>

						<el-form-item label="允许评论">
							<el-checkbox v-model="formData.commentFlag" :disabled="state == 3"></el-checkbox>
						</el-form-item>
						<el-form-item label="评论时间" prop="commentTimeAll">
              <div>
                <div v-if="state == 3">{{formData.commentTimeAll[0] | $timeReplaceFilter}} - {{formData.commentTimeAll[1] | $timeReplaceFilter}}</div>
                <el-date-picker v-else v-model="formData.commentTimeAll" type="daterange" value-format="yyyy/MM/dd"
                	style="width: 260px;"
                	range-separator="至"
                	start-placeholder="开始日期"
                	end-placeholder="结束日期"
                	>
                </el-date-picker>
              </div>
						</el-form-item>
					</el-col>
				</el-row>
			</el-form>
			<span slot="footer" class="dialog-footer">
				<el-button @click="show = false" :disabled="submitLoading">取 消</el-button>
				<el-button type="primary" v-if="state == 1" :disabled="submitLoading" :loading="submitLoading == 'save'" @click="newContent(0,'save')">保 存</el-button>
				<el-button type="primary" v-if="state == 1" :disabled="submitLoading" :loading="submitLoading == 'add'" @click="newContent(0,'add')">新 建</el-button>
				<el-button type="primary" v-if="state == 2" :disabled="submitLoading" :loading="submitLoading == 'edit'" @click="newContent(0,'edit')">修 改</el-button>
				<el-button type="primary" v-if="state != 3" :disabled="submitLoading" :loading="submitLoading == 'send'" @click="newContent(1,'sned')">发 布</el-button>
			</span>
			<up-loaidng v-model="upImageVal" ref="up-loading" @submit="upLoadingSubmit"></up-loaidng>

		</el-dialog>
		<!-- 抽屉 -->
		<el-drawer direction="ltr" title="选择栏目" :visible.sync="elDrawerShow"
		 :show-close="false"
		 :wrapperClosable="false"
		 :close-on-press-escape="false">
			<div class="el-drawer-relative">
				<div class="el-drawer-body">
					<el-tree :data="deptList" v-show="treeState == 1" @current-change="treeCheck" ref="tree_1" :props="defaultProps"></el-tree>
					<el-tree ref="tree_2" v-show="treeState!=1" :data="deptList"
						show-checkbox
						node-key="categoryId"
						:props="defaultProps">
					</el-tree>
				</div>
				<div class="el-drawer-btn">
					<el-button type="" @click="treeCancel">取 消</el-button>
					<el-button type="primary" @click="treeSubmit">确 定</el-button>
				</div>
			</div>
		</el-drawer>
    <!-- 预览pdf -->
    <el-dialog append-to-body title="预览" @closed="handlePreviewClose" :visible.sync="onlinePreview" width="900px" :close-on-click-modal="false">
      <div class="online-review-div" v-loading="!onlinePreviewFile" element-loading-text="拼命加载中">
        <video style="width: 850px;height:450px;" autoplay loop controls :src="onlinePreviewFile" v-if="onlinePreviewStatus == 'video'"></video>
        <el-image :src="onlinePreviewFile" style="width: 800px;height:450px;" v-if="onlinePreviewStatus == 'image'" fit="cover"></el-image>
        <see-pdf v-if="onlinePreviewStatus == 'office'" v-model="onlinePreviewFile" :height="850"></see-pdf>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="handlePreviewClose">关 闭</el-button>
        <el-button @click="handleDown" type="primary" :disabled="!onlinePreviewFile" :loading="handleDownLoading">下 载</el-button>
      </span>
    </el-dialog>
	</div>
</template>
<script>
	import QuillEdit from "@/components/Editor";
	import Treeselect from "@riophae/vue-treeselect";
	import UpLoaidng from "@/components/UpLoaidng";
  import SeePdf from "@/components/SeePdf";
	import "@riophae/vue-treeselect/dist/vue-treeselect.css";
	import { articleAdd,articleEdit,articleRemoveFile,articleDownloadFile,articleShowFileByte,articleFindFileList,articleSaveEcho } from "@/api/education/article";
	import { categoryFindList } from '@/api/education/column'
  import { getToken } from "@/utils/auth";
  import {dataURLtoBlob,blobToFile,_fileNmae,formRules} from "../content.js"
	export default {
		name: 'Article-add',
    props:{
      fullscreen:{
        type: Boolean,
        default: true
      }
    },
		components: {
			QuillEdit,
			Treeselect,
			UpLoaidng,
      SeePdf
		},
		data() {
			return {
				show: false,

				submitLoading:false,
				input: '',

				state: 1, //1 新建 2修改 3查看
				checked: true,
				deptList:[], //处理过的栏目列表
				dataTable:[], // 未处理过的栏目列表

				elDrawerShow: false,
				upImageVal: false,
				formData:{
					title:'',
					author:'',
					coverImage:'',
					publishTime:'',
					offlineTime:'',
					content:'',
					commentFlag:true,
					available: 0 ,//草稿
					categoryId: '',
					remarks1: '',
          remarks2: '', //附件
					commentEndTime: '',//允许评论结束时间
					commentStartTime: '' ,//允许评论开始时间
					commentTimeAll: '', //允许评论时间综合
				},
				formRules,
				treeData: [], //树选中
				treeState: 1, //单选
				defaultProps: {
					children: 'children',
					label: 'categoryName',
				},

				getCheckedKeys:[] ,//回显时候显示
				categoryIdName: '', //栏目的名字
				treeRadioData: '',
				id:'' ,// 修改id
        accept:'.png,.jpeg,.jpg,.xls,.pdf,.xlsx,.doc,.docx,.mp4' ,//文件类型
        removeConter: true, //附件移除控件提示

        fileList:[], //附件
        onlinePreview: false,
        onlinePreviewStatus: '' , //当前显示内容身份
        onlinePreviewFile: '',
        blobFile:{},
        handleDownLoading: false, //文件下载加载
			}
		},
		computed: {
			stateTitle() {
				switch (this.state) {
					case 1:
						return '新建文章'
					case 2:
						return '修改文章'
          case 3:
            return '查看文章'
					default:
						return '报错'
				}
			},
			images(){
				return process.env.VUE_APP_BASE_API + this.formData.coverImage
			},
			selectColumn(){
				if(this.treeData){
					let str = ''
					this.treeData.forEach(item=>{
						if(str){
							str = `${str},${item.categoryName}`
						}else{
							str = item.categoryName
						}
					})
					return str
				}
				return null
			},
      headers() {
      	return {
      		Authorization: "Bearer " + getToken()
      	}
      },
      uploadImgUrl() {
      	return process.env.VUE_APP_BASE_API + "/cms/file/uploadFile"
      }
		},
		created() {
			categoryFindList({}).then(res=>{
				this.deptList = this.handleTree(res.data, "categoryId");
				this.dataTable = res.data
			})
		},
		methods: {
      handleDown(){
        this.handleDownLoading = true
        articleDownloadFile(this.blobFile.dataId).then(res=>{
          this.handleDownLoading = false
          let url = `data:${res.data.type};base64,${res.data.finalbyte}`
          const a = document.createElement('a');//创建a标签
          a.setAttribute('download', res.data.file.fileOldName);// 名字
          a.setAttribute('href', url);// href链接
          a.click();					 // 自执行点击事件
          document.body.appendChild(a);//插入body里
          document.body.removeChild(a);//从body删除
        })
      },
      handlePreviewClose(){
        this.onlinePreview = false
        this.onlinePreviewFile = ''
        if(this.onlinePreviewFile) window.URL.revokeObjectURL(this.onlinePreviewFile) //清除缓存的url
      },
      beforeAvatarUpload(file){
        let format = file.name.split('.')
        format = format[format.length-1]
        if(this.accept.indexOf(format) == -1){
          this.$message.error('上传文件格式不正确')
          this.removeConter = false
          return false
        }
        if(file.size / 1024 / 1024 > 50){
          this.$message.error('文件大小不能超过50MB')
          this.removeConter = false
          return false
        }
        return true
      },
      beforeRemove(file){
        if(!this.removeConter){
            this.removeConter = true
            return true
        }
          return this.$confirm(`确定移除 ${ file.name }？`,{
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            beforeClose:(action, instance, done) => {
              if (action === 'confirm') {
                instance.confirmButtonLoading = true;
                instance.confirmButtonText = '执行中...';
                articleRemoveFile(file.dataId).then(res=>{
                  done();
                  instance.confirmButtonLoading = false;
                })
              } else {
                done();
              }
            }
          })
      },
      onPreview(file,options){
        this.onlinePreviewFile = ''
        this.onlinePreviewStatus = ''
        this.onlinePreview = true
        articleShowFileByte(file.dataId).then(res=>{
          if(res.data.file.fileType == 'mp4'){ //视频
          this.blobFile = blobToFile(dataURLtoBlob(`data:${res.data.type};base64,${res.data.finalbyte}`),_fileNmae(res.data.file.fileOldName,'mp4'),file.dataId)
          this.onlinePreviewFile = window.URL.createObjectURL(this.blobFile)
            this.onlinePreviewStatus = 'video'
            return false
          }
          if(res.data.file.fileType == 'png' || res.data.file.fileType == 'jpeg' || res.data.file.fileType == 'jpg'){ //图片
            this.blobFile = blobToFile(dataURLtoBlob(`data:${res.data.type};base64,${res.data.finalbyte}`),_fileNmae(res.data.file.fileOldName,res.data.file.fileType),file.dataId)
            this.onlinePreviewFile = window.URL.createObjectURL(this.blobFile)
            this.onlinePreviewStatus = 'image'
            return false
          }
          this.blobFile = blobToFile(dataURLtoBlob(`data:${res.data.type};base64,${res.data.finalbyte}`),_fileNmae(res.data.file.fileOldName,'pdf'),file.dataId)
          this.onlinePreviewFile = window.URL.createObjectURL(this.blobFile)
          this.onlinePreviewStatus = 'office'
        })
      },
      onSuccess(response, file, fileList){
        this.fileList = fileList.map(item=>{
            if(!item.dataId) item.dataId = item.response.data
            return item
        })
      },
      handleUpImage(){
        if(this.state == 3) return
        this.$refs['up-loading'].image = this.formData.coverImage || ''
        this.upImageVal= true
      },
			treeCheck(options){
				this.treeRadioData = options
			},
			treeCancel(){
				this.elDrawerShow = false
				if(this.treeState != 1){
					this.$refs['tree_2'].setCheckedKeys([])
				}
			},
			treeSubmit(){
				if(this.treeState == 1){
						this.elDrawerShow = false
						this.formData.categoryId = this.treeRadioData.categoryId
						this.categoryIdName = this.treeRadioData.categoryName
				}else{
					if(this.$refs['tree_2'].getCheckedKeys(false)){
						this.treeData = this.$refs['tree_2'].getCheckedNodes(false)
						this.formData.remarks1 = this.$refs['tree_2'].getCheckedKeys(false).toString()
						this.getCheckedKeys = this.$refs['tree_2'].getCheckedKeys(false)
						// 清空
						this.$refs['tree_2'].setCheckedKeys([])
						this.elDrawerShow = false
					}
				}
			},
			selectClick(numb){
				this.treeState = numb
				this.elDrawerShow = true
				if(numb != 1){
					setTimeout(()=>{
						this.$refs['tree_2'].setCheckedKeys(this.getCheckedKeys)
					},200)
				}
			},
			init(numb,options,fileList) {
				// 保存回显
				if(numb == 1) {
          articleSaveEcho().then(res=>{
            for(let i in this.formData){
            	this.formData[i] = res.data.article[i]
            }
            // 评论时间
            this.formData.commentTimeAll = [res.data.article.commentStartTime || '',res.data.article.commentEndTime || '']
            // 允许评论
            this.formData.commentFlag = res.data.article.commentFlag == 1 ? true : false
            this.echoContent()
          })
				}
				// 修改回显
				if(options && numb == 2 || numb == 3){
					this.id = options.article.id
					for(let i in this.formData){
						this.formData[i] = options.article[i]
					}
					// 评论时间
					this.formData.commentTimeAll = [options.article.commentStartTime || '',options.article.commentEndTime || '']
					// 允许评论
					this.formData.commentFlag = options.article.commentFlag == 1 ? true : false
          // 附件回显
          this.fileList = options.fileList.map(item=>{
            return {
              ...item,
              percentage:100,
              name:item.fileOldName,
              size:item.fileSize,
              dataId: item.id,
              uid: item.id
            }
          })
          // 规则显示
          if(numb == 3){
            let _formRules = {...formRules}
             for(let i in _formRules){
               _formRules[i].required = false
             }
          }else{
            this.formRules = formRules
          }
					this.echoContent()
				}
				this.state = numb
				this.show = true
			},
			echoContent(){
				this.dataTable.forEach(item=>{
					if(item.categoryId == this.formData.categoryId){ //所属栏目回显
						this.categoryIdName = item.categoryName
					}
					if(this.formData.remarks1){ //同时发布回显
						let arr = this.formData.remarks1.split(',')
						arr.forEach(id => {
							if(id == item.categoryId){
								this.treeData.push( item )
							}
						})
					}
				})
			},
			newContent(available,str){
        if(Array.isArray(this.fileList) && this.fileList.length){
            this.formData.remarks2 = this.fileList.map(item=>{
               return item.dataId
            }).toString()
        }
				let obj = {...this.formData}
				obj.commentStartTime = obj.commentTimeAll[0]
				obj.commentEndTime = obj.commentTimeAll[1]
				obj.commentFlag = this.formData.commentFlag ? 'on' : 'off'
				obj.available = available
				delete obj.commentTimeAll
				this.$refs['formData'].validate((valid)=>{
					if(valid){
						this.submitLoading = str
						if(str == 'edit'){ //修改
							let data = {...obj,id:this.id}
							articleEdit(data).then(res=>{
								this.submitLoading = ''
								this.cancel()
								this.$emit('submit-success')
							})
						}else{ //新建
							articleAdd(obj).then(res=>{
								this.submitLoading = ''
								this.cancel()
								this.$emit('submit-success')
							})
						}
					}
				})
			},
			upImageSucces(options){
				console.log('上传图片成功',options)
			},
			/** 转换部门数据结构 */
			normalizer(node) {
				if (node.children && !node.children.length) {
					delete node.children;
				}
				return {
					id: node.deptId,
					label: node.deptName,
					children: node.children
				};
			},
			cancel(){
				this.show = false
				for(let i in this.formData){
					this.formData[i] = ''
					if(i == 'commentFlag') this.formData[i] = true
					if(i == 'available') this.formData[i] = 0
				}
				this.treeData = []
        this.fileList = []
				this.getCheckedKeys = []
				this.categoryIdName = ''
				this.treeRadioData = ''
				this.id = ''
				this.submitLoading = false
        this.handleDownLoading = false
				this.$refs['formData'].clearValidate()  //移除表单校验
			},
			upLoadingSubmit(options){ //赋值封面图
				this.formData.coverImage = options.url
			}
		},
	}
</script>
<style lang="scss" scoped>
  .quill-div{
    height: 465px;
    overflow-y: auto;
  }
  ::v-deep .upload-demo-look ul{
    margin-top: -38px;
  }
  .online-review-div{
    display: flex;
    align-items: center;
    flex-direction: column;
  }
	.select-column{
		min-height: 36px;
		width: 200px;
		border: 1px solid #DCDFE6;
		border-radius: 4px;
		box-sizing: border-box;
		padding:0 15px;
		cursor: pointer;
		position: relative;
		.el-icon-arrow-right{
			position: absolute;
			top: 50%;
			right: 6px;
			transform: translate(0, -50%);
		}
	}
	.el-drawer-relative {
		position: relative;
		height: 100%;

		.el-drawer-btn {
			position: absolute;
			bottom: 10px;
			right: 5px;
		}

		.el-drawer-body {
			position: absolute;
			top: 0;
			right: 0;
			left: 0;
			overflow-y: auto;
			bottom: 50px;
		}
	}
</style>
